from django.shortcuts import render,HttpResponse
import json,requests,time,re
from bs4 import BeautifulSoup
# Create your views here.
"""
1.消息群发
2.清理僵尸好友
3.消息定时发送
4.语音转发
5.刷微信消息

"""
CODE=""
TIP=0
COOKIES={}
CTIME=str(time.time())
DICT={}
USER_INFO={}
def login(request):
    URL='https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_=%s'%CTIME
    respone=requests.request(
        url=URL,
        method='get',
        headers={
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',
            'Referer':'https://wx.qq.com/'
        }
    )
    global CODE
    CODE=respone.text.split('"')[1]
    return render(request,'login.html',{'code':CODE})

def check_login(request):
    URL='https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=%s&tip=%s&r=-1936666409&_=%s'%(CODE,TIP,CTIME)
    r1=requests.get(
        url=URL
    )
    res={'code':None}
    print('---------------',r1.text)
    if '408' in r1.text:
        print('无人扫码')
        res['code']=408
    elif 'window.code=201' in r1.text:
        print('已经扫码，请手机上点击确认按钮！')
        res['code']=201
        imgpath=re.findall("window.userAvatar = '(.*)';",r1.text)
        print('---------',imgpath)
        res['imgpath']=imgpath
    elif 'window.code=200' in r1.text:
        print('已确认登陆，正在授权')
        res['code']=200
        redrict_url=re.findall('redirect_uri="(.*)"',r1.text)[0]
        redrict_url+='&fun=new&version=v2&lang=zh_CN'
        print('redrict_url:',redrict_url)
        r2=requests.get(redrict_url)
        COOKIES.update(r2.cookies.get_dict())
        soup=BeautifulSoup(r2.text,features='lxml')
        for tag in soup.find('error').children:
            DICT[tag.name]=tag.string

    return HttpResponse(json.dumps(res))


def user(request):
    json_data={
        "BaseRequest":{
                       "Uin":DICT['wxuin'],
                       "Sid": DICT['wxsid'],
                       "Skey":DICT['skey']
                       },
        "DeviceID":"e301257987250377",
        "Sid":DICT['wxsid'],
        "Skey":DICT['skey'],
        "Uin":DICT['wxuin']
    }
    #获取用户个人信息
    url1='https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=-2015355380&lang=zh_CN&pass_ticket=%s'%DICT['pass_ticket']
    respone=requests.post(
        url=url1,
        json=json_data
    )
    respone.encoding='utf-8'
    userinfo=json.loads(respone.text)['User']
    USER_INFO['username']=userinfo['NickName']
    USER_INFO['id']=userinfo['UserName']
    USER_INFO['Signature']=userinfo['Signature']
    USER_INFO['sex']=userinfo['Sex']


    #获取所有联系人
    url='https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket=%s&r=1543913826350&seq=0&skey=%s'%(DICT['pass_ticket'],DICT['skey'])
    r1=requests.post(
        url=url,
        json=json_data,
        cookies=COOKIES,
        headers={
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',
            'Referer':'https://wx.qq.com/'
        }

    )
    r1.encoding = 'utf-8'
    USER_INFO_DICT=json.loads(r1.text)

    return render(request,'user.html',{'user':USER_INFO_DICT})


def friend(request):
    pass

def send_msg(request):
    ids=request.POST.get('users')
    ids=json.loads(ids)
    msg=request.POST.get('msg')
    status=True
    for user_id in ids:
        ctime=time.time()
        post_dict = {
            'BaseRequest': {
                'DeviceID': "e402310790089148",
                'Sid':DICT['wxsid'],
                'Uin':DICT['wxuin'],
                'Skey':DICT['skey'],
            },
            "Msg": {
                'ClientMsgId': ctime,
                'Content': msg,
                'FromUserName':USER_INFO['id'],
                'LocalID': ctime,
                'ToUserName': user_id,
                'Type': 1
            },
            'Scene':0
        }
        url="https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket=%s"%DICT['pass_ticket']
        r1=requests.post(
            url=url,
            data=bytes(json.dumps(post_dict,ensure_ascii=False),encoding='utf-8'),
            cookies=COOKIES
        )

        res=json.loads(r1.text)
        if res['BaseResponse']['Ret']==0 and  len(res['BaseResponse']['ErrMsg'])==0:
            pass
        else:
            status=False
    res_dict={}
    if status:
        res_dict['code']=200
        res_dict['status']='消息发送成功！！'
    else:
        res_dict['code']=500
        res_dict['status']='出现未知错误，请联系管理员！！'

    return HttpResponse(json.dumps(res_dict,ensure_ascii=False))